<template>
  <view class="container">
    <!-- 游戏标题和控制区 -->
    <view class="game-header">
      <text class="text-2xl font-bold mb-6">拼图小游戏</text>

      <view class="game-controls flex justify-between items-center mb-6">
        <view class="game-stats bg-gray-100 p-4 rounded-lg shadow-sm">
          <view class="flex items-center mb-2">
            <i class="fa fa-clock-o text-blue-500 mr-2"></i>
            <text>时间: {{ formatTime(time) }}</text>
          </view>
          <view class="flex items-center">
            <i class="fa fa-step-forward text-green-500 mr-2"></i>
            <text>步数: {{ moves }}</text>
          </view>
        </view>

        <view class="game-options">
          <view class="mb-3">
            <text class="block mb-1 text-sm">难度级别</text>
            <picker @change="handleLevelChange" :value="levelIndex" :range="levels" class="w-full">
              <view class="picker-view border border-gray-200 rounded p-2 bg-white">
                {{ levels[levelIndex] }}
              </view>
            </picker>
          </view>

          <button @click="startGame"
            class="start-btn bg-blue-500 text-white py-2 px-6 rounded-md hover:bg-blue-600 transition-all duration-300">
            开始游戏
          </button>
        </view>
      </view>
    </view>

    <!-- 拼图区域 -->
    <view v-if="isPlaying" class="puzzle-container" :style="{
      gridTemplateColumns: `repeat(${size}, 1fr)`,
      width: `${puzzleSize}px`,
      height: `${puzzleSize}px`,
      margin: '0 auto'
    }">
      <view v-for="(piece, index) in puzzlePieces" :key="index" class="puzzle-piece" :style="{
          backgroundImage: `url(${imageUrl})`,
          backgroundPosition: `-${piece.x}px -${piece.y}px`,
          backgroundSize: `${puzzleSize}px ${puzzleSize}px`,
          width: `${pieceSize}px`,
          height: `${pieceSize}px`,
          border: '1px solid #fff',
          cursor: 'pointer',
          opacity: piece.isEmpty ? 0 : 1,
          transition: 'transform 0.2s ease'
        }" @click="handlePieceClick(index)" :class="{ 'empty-piece': piece.isEmpty }"></view>
    </view>

    <!-- 完成提示 -->
    <view v-if="isCompleted" class="completion-modal">
      <view class="modal-content bg-white rounded-xl p-6 shadow-xl transform transition-all">
        <text class="text-xl font-bold mb-4 block text-center">恭喜完成!</text>
        <view class="text-center mb-4">
          <text class="block mb-1">用时: {{ formatTime(time) }}</text>
          <text class="block">步数: {{ moves }}</text>
        </view>
        <button @click="startGame"
          class="w-full mt-2 bg-green-500 text-white py-2 px-4 rounded-md hover:bg-green-600 transition-all duration-300">
          再来一局
        </button>
      </view>
    </view>

    <!-- 初始图片选择 -->
    <view v-if="!isPlaying && !isCompleted" class="image-selection">
      <text class="text-xl font-bold mb-6 block text-center">选择拼图图片</text>
      <view class="image-grid grid grid-cols-3 gap-4">
        <view v-for="(img, idx) in imageOptions" :key="idx" class="image-option" @click="selectImage(img.url)">
          <image :src="img.url" mode="widthFix"
            class="w-full h-24 object-cover rounded shadow hover:opacity-80 transition-all duration-300"></image>
          <text class="text-center mt-1 text-sm block">{{ img.name }}</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
  import {
    ref,
    onMounted,
    computed,
    watch
  } from 'vue';

  // 游戏状态
  const isPlaying = ref(false);
  const isCompleted = ref(false);
  const time = ref(0);
  const moves = ref(0);
  const timer = ref(null);

  // 拼图配置
  const levels = ['简单 (3x3)', '中等 (4x4)', '困难 (5x5)'];
  const levelIndex = ref(0);
  const size = ref(3); // 3x3, 4x4, 5x5
  const puzzleSize = ref(300); // 拼图总大小
  const pieceSize = computed(() => puzzleSize.value / size.value);

  // 图片选择
  const imageUrl = ref('');
  const imageOptions = [{
      url: 'https://picsum.photos/id/1/300/300',
      name: '山水'
    },
    {
      url: 'https://picsum.photos/id/20/300/300',
      name: '森林'
    },
    {
      url: 'https://picsum.photos/id/26/300/300',
      name: '海岸'
    },
    {
      url: 'https://picsum.photos/id/65/300/300',
      name: '动物'
    },
    {
      url: 'https://picsum.photos/id/96/300/300',
      name: '猫咪'
    },
    {
      url: 'https://picsum.photos/id/160/300/300',
      name: '城市'
    },
  ];
  const puzzlePieces = ref([]);

  // 格式化时间显示
  const formatTime = (seconds) => {
    const mins = Math.floor(seconds / 60);
    const secs = seconds % 60;
    return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
  };

  // 处理难度级别变化
  const handleLevelChange = (e) => {
    levelIndex.value = e.detail.value;
    switch (levelIndex.value) {
      case 0:
        size.value = 3;
        break;
      case 1:
        size.value = 4;
        break;
      case 2:
        size.value = 5;
        break;
    }
  };

  // 选择图片
  const selectImage = (url) => {
    imageUrl.value = url;
    isPlaying.value = true;
    startGame();
  };

  // 初始化拼图
  const initializePuzzle = () => {
    const pieces = [];

    // 创建所有拼图块
    for (let y = 0; y < size.value; y++) {
      for (let x = 0; x < size.value; x++) {
        pieces.push({
          x: x * pieceSize.value,
          y: y * pieceSize.value,
          correctX: x * pieceSize.value,
          correctY: y * pieceSize.value,
          isEmpty: false
        });
      }
    }

    // 设置最后一块为空
    pieces[pieces.length - 1].isEmpty = true;

    puzzlePieces.value = pieces;

    // 打乱拼图
    shufflePuzzle();
  };

  // 打乱拼图
  const shufflePuzzle = () => {
    // 执行足够多次随机移动来打乱拼图
    let emptyIndex = puzzlePieces.value.findIndex(piece => piece.isEmpty);

    // 打乱次数随难度增加
    const shuffleTimes = size.value * size.value * 10;
    for (let i = 0; i < shuffleTimes; i++) {
      const neighbors = getNeighbors(emptyIndex);
      const randomNeighbor = neighbors[Math.floor(Math.random() * neighbors.length)];

      // 交换空白块和随机邻居
      [puzzlePieces.value[emptyIndex], puzzlePieces.value[randomNeighbor]] = [puzzlePieces.value[randomNeighbor],
        puzzlePieces.value[emptyIndex]
      ];

      emptyIndex = randomNeighbor;
    }
  };

  // 获取空白块的邻居
  const getNeighbors = (index) => {
    const neighbors = [];
    const row = Math.floor(index / size.value);
    const col = index % size.value;

    // 上
    if (row > 0) neighbors.push(index - size.value);
    // 下
    if (row < size.value - 1) neighbors.push(index + size.value);
    // 左
    if (col > 0) neighbors.push(index - 1);
    // 右
    if (col < size.value - 1) neighbors.push(index + 1);

    return neighbors;
  };

  // 处理拼图块点击
  const handlePieceClick = (index) => {
    const emptyIndex = puzzlePieces.value.findIndex(piece => piece.isEmpty);
    const neighbors = getNeighbors(emptyIndex);

    // 如果点击的是空白块的邻居，则交换位置
    if (neighbors.includes(index)) {
      // 交换位置
      [puzzlePieces.value[emptyIndex], puzzlePieces.value[index]] = [puzzlePieces.value[index], puzzlePieces.value[
        emptyIndex]];

      moves.value++;

      // 检查是否完成
      checkCompletion();
    }
  };

  // 检查是否完成拼图
  const checkCompletion = () => {
    for (let i = 0; i < puzzlePieces.value.length; i++) {
      const piece = puzzlePieces.value[i];
      // 除了最后一块空白块，其他都要位置正确
      if (!piece.isEmpty && (piece.x !== piece.correctX || piece.y !== piece.correctY)) {
        return false;
      }
    }

    // 完成拼图
    isCompleted.value = true;
    clearInterval(timer.value);
    return true;
  };

  // 开始游戏
  const startGame = () => {
    if (timer.value) clearInterval(timer.value);

    time.value = 0;
    moves.value = 0;
    isCompleted.value = false;

    initializePuzzle();

    // 启动计时器
    timer.value = setInterval(() => {
      time.value++;
    }, 1000);
  };

  // 监听游戏状态变化
  watch([isCompleted, isPlaying], () => {
    if (isCompleted.value || !isPlaying.value) {
      clearInterval(timer.value);
    }
  });

  onMounted(() => {
    // 初始化时选择第一张图片
    imageUrl.value = imageOptions[0].url;
  });
</script>

<style scoped>
  .container {
    padding: 20rpx;
    max-width: 600px;
    margin: 0 auto;
    min-height: 100vh;
    background-color: #f9f9f9;
  }

  .game-header {
    text-align: center;
    padding-top: 20rpx;
  }

  .game-controls {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    flex-wrap: wrap;
    gap: 20rpx;
  }

  .puzzle-container {
    display: grid;
    background-color: #eee;
    border: 2px solid #333;
    position: relative;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    border-radius: 4rpx;
  }

  .puzzle-piece {
    transition: all 0.2s ease;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: bold;
    background-repeat: no-repeat;
    user-select: none;
  }

  .puzzle-piece:hover:not(.empty-piece) {
    transform: scale(1.02);
    box-shadow: 0 0 10rpx rgba(0, 0, 0, 0.3);
    z-index: 10;
  }

  .empty-piece {
    background-color: #ddd;
    border: 1px solid #bbb;
  }

  .completion-modal {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 100;
  }

  .modal-content {
    animation: popIn 0.3s ease-out;
  }

  @keyframes popIn {
    0% {
      transform: scale(0.8);
      opacity: 0;
    }

    100% {
      transform: scale(1);
      opacity: 1;
    }
  }

  .image-selection {
    text-align: center;
    margin-top: 30rpx;
  }

  .image-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 15rpx;
  }

  .image-option {
    cursor: pointer;
  }

  .picker-view {
    padding: 10rpx;
    border: 1px solid #ddd;
    border-radius: 5rpx;
    background-color: white;
  }
</style>